import 'package:flutter/material.dart';
import 'package:klcpopup/klcpopup.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qilo/core/constants/app_colors.dart';
import 'package:qilo/core/constants/app_icons.dart';
import 'package:url_launcher/url_launcher.dart';

/// 通知协调器 - 用于显示各种类型的提示
class NotificationCoordinator {
  static NotificationCoordinator? _instance;

  NotificationCoordinator._internal();

  factory NotificationCoordinator() {
    _instance ??= NotificationCoordinator._internal();
    return _instance!;
  }

  /// 显示成功提示
  static void showSuccessAlert(
    BuildContext context, {
    required String message,
    String? title,
    Duration duration = const Duration(seconds: 3),
    VoidCallback? onTap,
  }) {
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.none,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 50.h),
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: const Color(0xFF4CAF50),
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.2),
                blurRadius: 10,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: InkWell(
            onTap: onTap ?? () => popupController.dismiss(),
            child: Row(
              children: [
                Icon(
                  Icons.check_circle_outline,
                  color: Colors.white,
                  size: 24.sp,
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (title != null) ...[
                        Text(
                          title,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4.h),
                      ],
                      Text(
                        message,
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

    // 自动关闭
    Future.delayed(duration, () {
      popupController.dismiss();
    });
  }

  /// 显示错误提示
  static void showErrorAlert(
    BuildContext context, {
    required String message,
    String? title,
    Duration duration = const Duration(seconds: 4),
    VoidCallback? onTap,
  }) {
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.none,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 50.h),
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: const Color(0xFFF44336),
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.2),
                blurRadius: 10,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: InkWell(
            onTap: onTap ?? () => popupController.dismiss(),
            child: Row(
              children: [
                Icon(Icons.error_outline, color: Colors.white, size: 24.sp),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (title != null) ...[
                        Text(
                          title,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4.h),
                      ],
                      Text(
                        message,
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

    // 自动关闭
    Future.delayed(duration, () {
      popupController.dismiss();
    });
  }

  /// 显示警告提示
  static void showWarningAlert(
    BuildContext context, {
    required String message,
    String? title,
    Duration duration = const Duration(seconds: 3),
    VoidCallback? onTap,
  }) {
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.none,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 50.h),
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: const Color(0xFFFF9800),
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.2),
                blurRadius: 10,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: InkWell(
            onTap: onTap ?? () => popupController.dismiss(),
            child: Row(
              children: [
                Icon(
                  Icons.warning_amber_outlined,
                  color: Colors.white,
                  size: 24.sp,
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (title != null) ...[
                        Text(
                          title,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4.h),
                      ],
                      Text(
                        message,
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

    // 自动关闭
    Future.delayed(duration, () {
      popupController.dismiss();
    });
  }

  /// 显示普通信息提示
  static void showInfoAlert(
    BuildContext context, {
    required String message,
    String? title,
    Duration duration = const Duration(seconds: 3),
    VoidCallback? onTap,
  }) {
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.none,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 50.h),
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: const Color(0xFF2196F3),
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.2),
                blurRadius: 10,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: InkWell(
            onTap: onTap ?? () => popupController.dismiss(),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.white, size: 24.sp),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (title != null) ...[
                        Text(
                          title,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4.h),
                      ],
                      Text(
                        message,
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

    // 自动关闭
    Future.delayed(duration, () {
      popupController.dismiss();
    });
  }

  /// 显示加载提示
  static KLCPopupController? _loadingController;

  static void showLoadingAlert(
    BuildContext context, {
    String message = 'Loading...',
    Color backgroundColor = const Color(0xFF424242),
  }) {
    _loadingController = KLCPopupController();

    showKLCPopup(
      context,
      controller: _loadingController!,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.dimmed,
      child: Material(
        color: Colors.transparent,
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: backgroundColor,
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 30.w,
                height: 30.w,
                child: const CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ),
              SizedBox(height: 16.h),
              Text(
                message,
                style: TextStyle(color: Colors.white, fontSize: 14.sp),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 隐藏加载提示
  static void hideLoadingAlert(BuildContext context) {
    _loadingController?.dismiss();
    _loadingController = null;
  }

  /// 显示确认对话框
  static void showConfirmationDialog(
    BuildContext context, {
    required String message,
    String? title,
    String confirmText = 'Confirm',
    String cancelText = 'Cancel',
    required VoidCallback onConfirm,
    VoidCallback? onCancel,
  }) {
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.none,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 40.w),
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (title != null) ...[
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 12.h),
              ],
              Text(
                message,
                style: TextStyle(fontSize: 16.sp, color: Colors.black54),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 20.h),
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () {
                        popupController.dismiss();
                        onCancel?.call();
                      },
                      child: Text(
                        cancelText,
                        style: TextStyle(color: Colors.grey, fontSize: 16.sp),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {
                        popupController.dismiss();
                        onConfirm();
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.iconColor,
                      ),
                      child: Text(
                        confirmText,
                        style: TextStyle(color: Colors.white, fontSize: 16.sp),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示需要登录提示弹窗
  static void showLoginRequiredDialog(
    BuildContext context, {
    String message = 'This feature requires login to use.',
    String? title,
    String loginText = 'Go to Login',
    String cancelText = 'Cancel',
    required VoidCallback onLogin,
    VoidCallback? onCancel,
  }) {
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.dimmed,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 40.w),
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 20,
                offset: const Offset(0, 10),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 登录图标
              Container(
                width: 60.w,
                height: 60.w,
                decoration: BoxDecoration(
                  color: AppColors.iconColor.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(30.r),
                ),
                child: Icon(
                  MyIcons.iconPeople,
                  size: 30.sp,
                  color: AppColors.iconColor,
                ),
              ),
              SizedBox(height: 16.h),

              // 标题
              if (title != null) ...[
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 8.h),
              ],

              // 消息内容
              Text(
                message,
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.black54,
                  height: 1.4,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 24.h),

              // 按钮区域
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () {
                        popupController.dismiss();
                        onCancel?.call();
                      },
                      style: TextButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                      ),
                      child: Text(
                        cancelText,
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {
                        popupController.dismiss();
                        onLogin();
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.iconColor,
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        elevation: 0,
                      ),
                      child: Text(
                        loginText,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示编辑用户名对话框
  static void showEditUsernameDialog(
    BuildContext context, {
    required String currentUsername,
    String title = 'Edit Username',
    String confirmText = 'Save',
    String cancelText = 'Cancel',
    required Function(String) onConfirm,
    VoidCallback? onCancel,
  }) {
    final TextEditingController controller = TextEditingController(
      text: currentUsername,
    );
    final popupController = KLCPopupController();

    showKLCPopup(
      context,
      controller: popupController,
      verticalLayout: KLCPopupVerticalLayout.center,
      horizontalLayout: KLCPopupHorizontalLayout.center,
      showType: KLCPopupShowType.bounceIn,
      dismissType: KLCPopupDismissType.bounceOutToBottom,
      maskType: KLCPopupMaskType.dimmed,
      child: Material(
        color: Colors.transparent,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 40.w),
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 20,
                offset: const Offset(0, 10),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              Text(
                title,
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              SizedBox(height: 16.h),

              // 输入框
              TextField(
                controller: controller,
                autofocus: true,
                decoration: InputDecoration(
                  hintText: 'Enter username',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(color: Colors.grey[300]!),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(color: AppColors.iconColor),
                  ),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 12.h,
                  ),
                ),
                style: TextStyle(fontSize: 16.sp, color: Colors.black87),
              ),
              SizedBox(height: 24.h),

              // 按钮区域
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () {
                        popupController.dismiss();
                        onCancel?.call();
                      },
                      style: TextButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                      ),
                      child: Text(
                        cancelText,
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {
                        final newUsername = controller.text.trim();
                        if (newUsername.isNotEmpty) {
                          popupController.dismiss();
                          onConfirm(newUsername);
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.iconColor,
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        elevation: 0,
                      ),
                      child: Text(
                        confirmText,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 打开网址
  static Future<void> openUrl(String url) async {
    try {
      final Uri uri = Uri.parse(url);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      } else {
        throw 'Could not launch $url';
      }
    } catch (e) {
      debugPrint('Error opening URL: $e');
    }
  }
}
